package com.dataStructure.model;

public class Person implements java.lang.Comparable<Person> {
    private int age;
    private float height;
    private String name;

    public Person(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public Person(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int compareTo(Person o) {
        //如果年龄比较大就大
        if (this.age > o.getAge())return 1;
        if (this.age < o.getAge()) return -1;
        return 0;
        //return this.age - o.age;
    }

    /**
     * 只重写equals 导致对象存储在hash表上不稳定，如果在同一个bucket上，相同的对象会进行覆盖，如果不在一个bucket上，则不会覆盖
     * 只重写hashCode 始终在一个bucket上，导致明明相同的两个对象，却因为没有重写equals导致两个相同的对象同时存在在一个bucket上
     * @return
     */

    @Override
    public int hashCode() {
        int hashCode = Integer.hashCode(age);
        hashCode = hashCode * 31 + Float.hashCode(height);
        hashCode = hashCode * 31 + (name != null ? name.hashCode() : 0);
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null || obj.getClass() != this.getClass()) return false;
        //使用instanceof的话 person的子类也会返回true
        //if (obj == null || !(obj instanceof Person)) return false;


        Person person = (Person)obj;
        return person.age == this.age
                &&(person.name == null ? this.name == null : person.name.equals(this.name))
                &&person.height == this.height;
    }
}
